package telebase;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.TreeMap;

public class ContObj {

    private Integer ID = -1;
    private String Name = "";
    private TreeMap<Integer, String> Works = new TreeMap<Integer, String>();
    private TreeMap<Integer, String> Phones = new TreeMap<Integer, String>();

    public ContObj(Integer id) {
        ID = id;

        DB db = new DB();

        Name = (String) db.getScalar("select contactname from contacts where k=" + ID);

        ResultSet rs;
        rs = db.getResultSet("select k, phone, description from phones where contactid=" + ID);
        try {
            while (rs.next()) {
                Phones.put(rs.getInt("k"), rs.getString("phone") + " (" + rs.getString("description") + ")");
            }
        } catch (SQLException ex) {
            System.out.println("ContObj (in phones): " + ex.toString());
        }
        db.closeResultSet();

        ArrayList<Integer> WorkIDs = new ArrayList<Integer>();
        rs = db.getResultSet("select workid from works where contactid=" + ID);
        try {
            while (rs.next()) {
                WorkIDs.add(rs.getInt("workid"));
            }
        } catch (SQLException ex) {
            System.out.println("ContObj (in works): " + ex.toString());
        }
        db.closeResultSet();

        String s;
        Integer k;
        for (Integer par : WorkIDs) {
            s = "";
            k = par;
            Boolean nextparent = true;
            while (nextparent) {
                rs = db.getResultSet("SELECT k, workpar, workname FROM worknames WHERE k=" + par);
                try {
                    rs.next();
                    par = rs.getInt("workpar");
                    if (s.equals("")) {
                        s = rs.getString("workname");
                    } else {
                        s = rs.getString("workname") + ", " + s;
                    }
                } catch (SQLException ex) {
                    System.out.println("ContObj (in Jobs): " + ex.toString());
                    db.closeResultSet();
                    break;
                }
                db.closeResultSet();

                if (par.equals(0)) {
                    nextparent = false;
                }
            }
            Works.put(k, s);
        }
    }

    public TreeMap<Integer, String> getWorks() {
        return Works;
    }

    public String getName() {
        return Name;
    }

    public TreeMap<Integer, String> getPhones() {
        return Phones;
    }

    public Integer getID() {
        return ID;
    }

    @Override
    public String toString() {
        return Name;
    }
}
